import React, { useState, useEffect, useRef } from 'react';
import { 
  Table, Card, Button, Modal, Form, Input, Select, Space, 
  Tooltip, Tag, message, Drawer, Tabs, Typography, Row, Col,
  DatePicker, Statistic, Empty, Avatar, Badge, Divider, Popconfirm,
  Segmented, Spin, Progress, Pagination
} from 'antd';
import { 
  EditOutlined, UserOutlined, PhoneOutlined, EnvironmentOutlined,
  ShopOutlined, TagOutlined, InfoCircleOutlined, ExportOutlined,
  EyeOutlined, SearchOutlined, FileTextOutlined, DeleteOutlined,
  MessageOutlined, PlusOutlined, FilterOutlined, SortAscendingOutlined,
  CalendarOutlined, BarChartOutlined, StarOutlined, StarFilled,
  TableOutlined, AppstoreOutlined
} from '@ant-design/icons';
import api from '../../services/api';
import crmService from '../../services/crmService';
import moment from 'moment';
import { useNavigate } from 'react-router-dom';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

const CustomerManagement = () => {
  const [customers, setCustomers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [form] = Form.useForm();
  const [currentCustomer, setCurrentCustomer] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [recentMessages, setRecentMessages] = useState([]);
  const [exportLoading, setExportLoading] = useState(false);
  const [filterForm] = Form.useForm();
  const [filterModalVisible, setFilterModalVisible] = useState(false);
  const [filters, setFilters] = useState({});
  const [stats, setStats] = useState({
    total: 0,
    leads: 0,
    prospects: 0,
    customers: 0,
    inactive: 0
  });
  const [displayMode, setDisplayMode] = useState('table');
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [addForm] = Form.useForm();
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [sortedInfo, setSortedInfo] = useState({});
  const [pagination, setPagination] = useState({ 
    current: 1, 
    pageSize: 10, 
    total: 0,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条记录`
  });
  
  const navigate = useNavigate();
  const tableRef = useRef(null);

  useEffect(() => {
    fetchCustomers();
  }, [filters, pagination.current, pagination.pageSize, sortedInfo]);

  const fetchCustomers = async () => {
    setLoading(true);
    try {
      // 构建查询参数，包括筛选、排序和分页
      const params = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...filters
      };
      
      // 添加排序参数
      if (sortedInfo.columnKey && sortedInfo.order) {
        params.sortField = sortedInfo.columnKey;
        params.sortOrder = sortedInfo.order;
      }
      
      console.log('开始获取CRM客户数据，参数:', params);
      
      const response = await crmService.getAllContacts();
      console.log('获取到的CRM客户数据:', response);
      
      if (response && response.data && Array.isArray(response.data)) {
        // 处理可能的数据问题，确保每个对象都有预期的结构
        const validatedData = response.data.map(customer => ({
          id: customer.id || Math.random(),
          contactId: customer.contactId || 0,
          status: customer.status || 'lead',
          product: customer.product || '',
          quantity: customer.quantity || '',
          location: customer.location || '',
          notes: customer.notes || '',
          source: customer.source || '',
          industry: customer.industry || '',
          contact: {
            id: customer.contact?.id || 0,
            name: customer.contact?.name || '未知联系人',
            whatsappId: customer.contact?.whatsappId || '',
            profilePicUrl: customer.contact?.profilePicUrl || '',
            phoneNumber: customer.contact?.phoneNumber || ''
          },
          creator: customer.creator || null,
          createdAt: customer.createdAt || new Date().toISOString(),
          updatedAt: customer.updatedAt || new Date().toISOString(),
          lastMessageTime: customer.contact?.lastMessageTime || null,
          rating: customer.rating || 0,
          nextFollowUp: customer.nextFollowUp || null,
          dealSize: customer.dealSize || 0
        }));
        
        setCustomers(validatedData);
        
        // 更新分页信息
        setPagination({
          ...pagination,
          total: response.total || validatedData.length
        });
        
        // 更新统计信息
        if (response.stats) {
          setStats(response.stats);
        } else {
          // 如果后端没有返回统计信息，自行计算
          calculateStats(validatedData);
        }
      } else {
        console.error('获取客户列表返回格式不正确:', response);
        message.error('获取客户列表失败：数据格式不正确');
        setCustomers([]);
        setPagination({...pagination, total: 0});
      }
    } catch (error) {
      console.error('获取客户列表失败:', error);
      // 显示更详细的错误消息
      let errorMsg = '获取客户列表失败';
      
      if (error.response) {
        if (error.response.status === 500) {
          errorMsg = '服务器内部错误，请联系管理员';
        } else if (error.response.status === 401) {
          errorMsg = '未授权，请重新登录';
          // 重定向到登录页面
          setTimeout(() => {
            window.location.href = '/login';
          }, 2000);
        } else {
          errorMsg = error.response.data?.message || '请求失败';
        }
      } else if (error.request) {
        errorMsg = '无法连接到服务器，请检查网络';
      } else {
        errorMsg = error.message || '未知错误';
      }
      
      message.error(errorMsg);
      setCustomers([]);
      setPagination({...pagination, total: 0});
    } finally {
      setLoading(false);
    }
  };

  // 计算客户状态统计
  const calculateStats = (data) => {
    if (!Array.isArray(data)) return;
    
    const newStats = {
      total: data.length,
      leads: 0,
      prospects: 0,
      customers: 0,
      inactive: 0
    };
    
    data.forEach(customer => {
      switch (customer.status) {
        case 'lead':
          newStats.leads++;
          break;
        case 'prospect':
          newStats.prospects++;
          break;
        case 'customer':
          newStats.customers++;
          break;
        case 'inactive':
          newStats.inactive++;
          break;
        default:
          break;
      }
    });
    
    setStats(newStats);
  };

  // 处理表格分页变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(prevPagination => ({
      ...prevPagination,
      current: pagination.current,
      pageSize: pagination.pageSize
    }));
    
    setSortedInfo(sorter);
  };

  // 处理筛选条件提交
  const handleFilterSubmit = (values) => {
    const formattedFilters = {};
    
    // 处理日期范围
    if (values.dateRange && values.dateRange.length === 2) {
      formattedFilters.startDate = values.dateRange[0].format('YYYY-MM-DD');
      formattedFilters.endDate = values.dateRange[1].format('YYYY-MM-DD');
    }
    
    // 处理其他筛选条件
    ['status', 'industry', 'source'].forEach(key => {
      if (values[key]) {
        formattedFilters[key] = values[key];
      }
    });
    
    // 处理关键词搜索
    if (values.keyword) {
      formattedFilters.keyword = values.keyword;
    }
    
    // 应用筛选条件
    setFilters(formattedFilters);
    setFilterModalVisible(false);
    
    // 重置分页到第一页
    setPagination({
      ...pagination,
      current: 1
    });
  };

  // 清除所有筛选条件
  const handleClearFilters = () => {
    filterForm.resetFields();
    setFilters({});
    setFilterModalVisible(false);
    
    // 重置分页到第一页
    setPagination({
      ...pagination,
      current: 1
    });
  };

  const showEditModal = (customer) => {
    setCurrentCustomer(customer);
    form.setFieldsValue({
      status: customer.status,
      notes: customer.notes,
      industry: customer.industry,
      product: customer.product,
      quantity: customer.quantity,
      location: customer.location,
      source: customer.source
    });
    setEditModalVisible(true);
  };

  const showDetailDrawer = async (customer) => {
    setCurrentCustomer(customer);
    setDetailDrawerVisible(true);
    
    // 获取最近消息
    try {
      const response = await api.get(`/messages/${customer.contactId}/recent?limit=10`);
      setRecentMessages(response.data);
    } catch (error) {
      console.error('获取最近消息失败:', error);
    }
  };

  const handleEditModalCancel = () => {
    setEditModalVisible(false);
  };

  const handleDetailDrawerClose = () => {
    setDetailDrawerVisible(false);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      await crmService.updateContact(currentCustomer.id, values);
      message.success('客户信息更新成功');
      
      setEditModalVisible(false);
      fetchCustomers();
    } catch (error) {
      message.error('更新客户信息失败');
      console.error('更新客户信息失败:', error);
    }
  };

  const handleExportData = async () => {
    setExportLoading(true);
    try {
      const blob = await crmService.exportData();
      
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `CRM-Customers-${new Date().toISOString().split('T')[0]}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      message.success('客户数据导出成功');
    } catch (error) {
      message.error('导出客户数据失败');
      console.error('导出客户数据失败:', error);
    } finally {
      setExportLoading(false);
    }
  };

  const getColumnSearchProps = (dataIndex, title) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          placeholder={`搜索 ${title}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
            重置
          </Button>
        </Space>
      </div>
    ),
    filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
        : '',
    render: text => text
  });

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = clearFilters => {
    clearFilters();
    setSearchText('');
  };

  const getStatusTag = (status) => {
    const statusConfig = {
      'lead': { color: 'blue', text: '潜在客户' },
      'prospect': { color: 'purple', text: '意向客户' },
      'customer': { color: 'green', text: '成交客户' },
      'inactive': { color: 'gray', text: '非活跃客户' }
    };
    
    return (
      <Tag color={statusConfig[status]?.color || 'default'}>
        {statusConfig[status]?.text || status}
      </Tag>
    );
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: ['contact', 'name'],
      key: 'name',
      ...getColumnSearchProps('contact.name', '姓名'),
      render: (text, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar 
            src={record.contact.profilePicUrl}
            style={{ marginRight: 8, backgroundColor: '#1890ff' }}
            icon={<UserOutlined />}
          >
            {text?.charAt(0)}
          </Avatar>
          <div>
            <a onClick={() => showDetailDrawer(record)}>
              {text}
            </a>
            {record.rating > 0 && (
              <div>
                {Array.from({ length: 5 }).map((_, index) => (
                  <StarFilled 
                    key={index} 
                    style={{ 
                      fontSize: '12px',
                      color: index < record.rating ? '#faad14' : '#d9d9d9',
                      marginRight: '2px'
                    }} 
                  />
                ))}
              </div>
            )}
          </div>
        </div>
      ),
    },
    {
      title: '电话',
      dataIndex: ['contact', 'phoneNumber'],
      key: 'phoneNumber',
      render: (phone) => (
        <span>
          <PhoneOutlined style={{ marginRight: 8 }} />
          {phone}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '潜在客户', value: 'lead' },
        { text: '意向客户', value: 'prospect' },
        { text: '成交客户', value: 'customer' },
        { text: '非活跃客户', value: 'inactive' },
      ],
      onFilter: (value, record) => record.status === value,
      render: (status) => getStatusTag(status),
    },
    {
      title: '产品',
      dataIndex: 'product',
      key: 'product',
      ...getColumnSearchProps('product', '产品'),
    },
    {
      title: '行业',
      dataIndex: 'industry',
      key: 'industry',
      filters: [
        { text: '制造业', value: '制造业' },
        { text: '服务业', value: '服务业' },
        { text: '零售业', value: '零售业' },
        { text: '教育', value: '教育' },
        { text: '医疗', value: '医疗' },
        { text: '其他', value: '其他' },
      ],
      onFilter: (value, record) => record.industry === value,
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      sorter: true,
      render: (time) => moment(time).format('YYYY-MM-DD'),
    },
    {
      title: '最近联系',
      dataIndex: ['contact', 'lastMessageTime'],
      key: 'lastMessageTime',
      render: (time) => time ? moment(time).format('YYYY-MM-DD HH:mm') : '未联系',
      sorter: (a, b) => {
        const timeA = a.contact.lastMessageTime ? new Date(a.contact.lastMessageTime).getTime() : 0;
        const timeB = b.contact.lastMessageTime ? new Date(b.contact.lastMessageTime).getTime() : 0;
        return timeA - timeB;
      },
    },
    {
      title: '下次跟进',
      dataIndex: 'nextFollowUp',
      key: 'nextFollowUp',
      sorter: true,
      render: (date) => date ? (
        <div style={{
          display: 'flex',
          alignItems: 'center',
          color: moment(date).isBefore(moment(), 'day') ? '#ff4d4f' : 'inherit'
        }}>
          <CalendarOutlined style={{ marginRight: 4 }} />
          {moment(date).format('YYYY-MM-DD')}
        </div>
      ) : <Text type="secondary">未设置</Text>,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="primary" 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => showDetailDrawer(record)}
            />
          </Tooltip>
          <Tooltip title="发送消息">
            <Button 
              icon={<MessageOutlined />} 
              size="small"
              onClick={() => handleStartChat(record.contactId)}
            />
          </Tooltip>
          <Tooltip title="编辑信息">
            <Button 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => showEditModal(record)}
            />
          </Tooltip>
          <Tooltip title="删除客户">
            <Popconfirm
              title="确定要删除此客户吗？"
              onConfirm={() => handleDeleteCustomer(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                danger
                icon={<DeleteOutlined />} 
                size="small"
                loading={deleteLoading}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 打开添加客户对话框
  const showAddCustomerModal = () => {
    addForm.resetFields();
    setAddModalVisible(true);
  };

  // 提交添加客户表单
  const handleAddCustomer = async () => {
    try {
      const values = await addForm.validateFields();
      setLoading(true);
      
      // 格式化日期数据
      if (values.nextFollowUp) {
        values.nextFollowUp = values.nextFollowUp.format('YYYY-MM-DD');
      }
      
      const response = await crmService.addContact(values);
      message.success('添加客户成功');
      setAddModalVisible(false);
      
      // 刷新客户列表
      fetchCustomers();
    } catch (error) {
      console.error('添加客户失败:', error);
      message.error('添加客户失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 删除客户
  const handleDeleteCustomer = async (id) => {
    try {
      setDeleteLoading(true);
      await api.delete(`/contacts/crm/customers/${id}`);
      message.success('删除客户成功');
      
      // 刷新客户列表
      fetchCustomers();
    } catch (error) {
      console.error('删除客户失败:', error);
      message.error('删除客户失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    } finally {
      setDeleteLoading(false);
    }
  };

  // 批量删除客户
  const handleBatchDelete = async () => {
    if (!selectedRowKeys.length) {
      message.warn('请先选择要删除的客户');
      return;
    }
    
    try {
      setDeleteLoading(true);
      await api.delete('/contacts/crm/customers/batch', {
        data: { ids: selectedRowKeys }
      });
      message.success(`成功删除 ${selectedRowKeys.length} 个客户`);
      
      // 清空选择
      setSelectedRowKeys([]);
      
      // 刷新客户列表
      fetchCustomers();
    } catch (error) {
      console.error('批量删除客户失败:', error);
      message.error('批量删除客户失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    } finally {
      setDeleteLoading(false);
    }
  };

  // 处理评分变化
  const handleRatingChange = async (customerId, rating) => {
    try {
      await api.put(`/contacts/crm/customers/${customerId}/rating`, { rating });
      
      // 更新本地数据
      setCustomers(prevCustomers => 
        prevCustomers.map(customer => 
          customer.id === customerId ? {...customer, rating} : customer
        )
      );
    } catch (error) {
      console.error('更新客户评分失败:', error);
      message.error('更新客户评分失败');
    }
  };

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys) => {
      setSelectedRowKeys(selectedKeys);
    }
  };

  // 切换显示模式
  const handleDisplayModeChange = (value) => {
    setDisplayMode(value);
  };

  // 发起WhatsApp聊天
  const handleStartChat = (contactId) => {
    navigate(`/chat/${contactId}`);
  };

  return (
    <div className="customer-management-container">
      {/* 头部统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card bordered={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
            <Statistic
              title="客户总数"
              value={stats.total}
              prefix={<UserOutlined style={{ color: '#1890ff' }} />}
              valueStyle={{ color: '#1890ff', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card bordered={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
            <Statistic
              title="潜在客户"
              value={stats.leads}
              valueStyle={{ color: '#1890ff' }}
              suffix={<small style={{ fontSize: '14px', color: '#999' }}>({stats.total ? Math.round(stats.leads/stats.total*100) : 0}%)</small>}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card bordered={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
            <Statistic
              title="意向客户"
              value={stats.prospects}
              valueStyle={{ color: '#722ed1' }}
              suffix={<small style={{ fontSize: '14px', color: '#999' }}>({stats.total ? Math.round(stats.prospects/stats.total*100) : 0}%)</small>}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card bordered={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
            <Statistic
              title="成交客户"
              value={stats.customers}
              valueStyle={{ color: '#52c41a' }}
              suffix={<small style={{ fontSize: '14px', color: '#999' }}>({stats.total ? Math.round(stats.customers/stats.total*100) : 0}%)</small>}
            />
          </Card>
        </Col>
      </Row>
      
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <ShopOutlined style={{ marginRight: 8 }} />
            <span>CRM客户管理</span>
          </div>
        }
        extra={
          <Space>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定要删除所选的 ${selectedRowKeys.length} 个客户吗？`}
                onConfirm={handleBatchDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button 
                  danger 
                  icon={<DeleteOutlined />}
                  loading={deleteLoading}
                >
                  批量删除
                </Button>
              </Popconfirm>
            )}
            
            <Button 
              icon={<FilterOutlined />} 
              onClick={() => setFilterModalVisible(true)}
            >
              筛选
            </Button>
            
            <Segmented
              options={[
                {
                  value: 'table',
                  icon: <TableOutlined />,
                  label: '表格视图'
                },
                {
                  value: 'card',
                  icon: <AppstoreOutlined />,
                  label: '卡片视图'
                }
              ]}
              value={displayMode}
              onChange={handleDisplayModeChange}
            />
            
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={showAddCustomerModal}
            >
              添加客户
            </Button>
            
            <Button 
              type="primary" 
              icon={<ExportOutlined />} 
              onClick={handleExportData}
              loading={exportLoading}
            >
              导出数据
            </Button>
          </Space>
        }
        bordered={false}
        style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}
      >
        {/* 表格视图 */}
        {displayMode === 'table' && (
          <Table 
            columns={columns} 
            dataSource={customers} 
            rowKey="id" 
            loading={loading}
            pagination={pagination}
            rowSelection={rowSelection}
            onChange={handleTableChange}
            style={{ marginTop: 16 }}
            ref={tableRef}
          />
        )}
        
        {/* 卡片视图 */}
        {displayMode === 'card' && (
          <div style={{ marginTop: 16 }}>
            {loading ? (
              <Spin tip="加载中...">
                <div style={{ height: 400 }}></div>
              </Spin>
            ) : customers.length > 0 ? (
              <Row gutter={[16, 16]}>
                {customers.map(customer => (
                  <Col xs={24} sm={12} md={8} lg={6} key={customer.id}>
                    <Card
                      hoverable
                      style={{ marginBottom: 16 }}
                      actions={[
                        <Tooltip title="查看详情">
                          <EyeOutlined key="view" onClick={() => showDetailDrawer(customer)} />
                        </Tooltip>,
                        <Tooltip title="发送消息">
                          <MessageOutlined key="message" onClick={() => handleStartChat(customer.contactId)} />
                        </Tooltip>,
                        <Tooltip title="编辑信息">
                          <EditOutlined key="edit" onClick={() => showEditModal(customer)} />
                        </Tooltip>,
                      ]}
                    >
                      <Card.Meta
                        avatar={
                          <Avatar 
                            src={customer.contact.profilePicUrl}
                            style={{ backgroundColor: '#1890ff' }}
                          >
                            {customer.contact.name.charAt(0)}
                          </Avatar>
                        }
                        title={
                          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <span>{customer.contact.name}</span>
                            {getStatusTag(customer.status)}
                          </div>
                        }
                        description={
                          <div>
                            <div>
                              <PhoneOutlined style={{ marginRight: 5 }} />
                              {customer.contact.phoneNumber}
                            </div>
                            {customer.industry && (
                              <div>
                                <ShopOutlined style={{ marginRight: 5 }} />
                                {customer.industry}
                              </div>
                            )}
                            {customer.product && (
                              <div>
                                <TagOutlined style={{ marginRight: 5 }} />
                                {customer.product}
                              </div>
                            )}
                            <div style={{ marginTop: 5 }}>
                              {Array.from({ length: 5 }).map((_, index) => (
                                <StarOutlined 
                                  key={index} 
                                  style={{ 
                                    fontSize: '14px',
                                    color: index < customer.rating ? '#faad14' : '#d9d9d9',
                                    marginRight: '3px',
                                    cursor: 'pointer'
                                  }} 
                                  onClick={() => handleRatingChange(customer.id, index + 1)}
                                />
                              ))}
                            </div>
                          </div>
                        }
                      />
                    </Card>
                  </Col>
                ))}
              </Row>
            ) : (
              <Empty description="暂无客户数据" />
            )}
            
            {/* 卡片视图的分页 */}
            <div style={{ textAlign: 'right', marginTop: 16 }}>
              <Pagination
                current={pagination.current}
                pageSize={pagination.pageSize}
                total={pagination.total}
                showSizeChanger
                onChange={(page, pageSize) => {
                  setPagination({
                    ...pagination,
                    current: page,
                    pageSize
                  });
                }}
                showTotal={(total) => `共 ${total} 条记录`}
              />
            </div>
          </div>
        )}
      </Card>

      {/* 编辑客户对话框 */}
      <Modal
        title="编辑客户信息"
        open={editModalVisible}
        onCancel={handleEditModalCancel}
        onOk={handleSubmit}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          name="customerForm"
          initialValues={{ status: 'lead' }}
        >
          <Form.Item
            name="status"
            label="客户状态"
            rules={[{ required: true, message: '请选择客户状态' }]}
          >
            <Select>
              <Option value="lead">潜在客户</Option>
              <Option value="prospect">意向客户</Option>
              <Option value="customer">成交客户</Option>
              <Option value="inactive">非活跃客户</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="industry"
            label="行业"
          >
            <Select allowClear placeholder="选择行业">
              <Option value="制造业">制造业</Option>
              <Option value="服务业">服务业</Option>
              <Option value="零售业">零售业</Option>
              <Option value="教育">教育</Option>
              <Option value="医疗">医疗</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="product"
            label="产品/服务"
          >
            <Input placeholder="客户感兴趣的产品或服务" />
          </Form.Item>
          
          <Form.Item
            name="quantity"
            label="数量/规模"
          >
            <Input placeholder="意向采购数量或规模" />
          </Form.Item>
          
          <Form.Item
            name="location"
            label="位置"
          >
            <Input placeholder="客户所在地区" prefix={<EnvironmentOutlined />} />
          </Form.Item>
          
          <Form.Item
            name="source"
            label="客户来源"
          >
            <Select allowClear placeholder="选择客户来源">
              <Option value="推荐">推荐</Option>
              <Option value="网站">网站</Option>
              <Option value="广告">广告</Option>
              <Option value="展会">展会</Option>
              <Option value="社交媒体">社交媒体</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="nextFollowUp"
            label="下次跟进时间"
          >
            <DatePicker 
              style={{ width: '100%' }} 
              placeholder="选择跟进日期"
              format="YYYY-MM-DD"
            />
          </Form.Item>
          
          <Form.Item
            name="notes"
            label="备注"
          >
            <TextArea rows={4} placeholder="添加客户备注信息" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 客户详情抽屉 */}
      <Drawer
        title={currentCustomer?.contact?.name || '客户详情'}
        placement="right"
        width={600}
        onClose={handleDetailDrawerClose}
        open={detailDrawerVisible}
        destroyOnClose={true}
        getContainer={false}
        style={{ position: 'absolute' }}
        extra={
          <Space>
            <Button 
              icon={<MessageOutlined />}
              onClick={() => {
                handleDetailDrawerClose();
                if (currentCustomer) {
                  handleStartChat(currentCustomer.contactId);
                }
              }}
            >
              发送消息
            </Button>
            <Button 
              type="primary" 
              icon={<EditOutlined />} 
              onClick={() => {
                handleDetailDrawerClose();
                showEditModal(currentCustomer);
              }}
            >
              编辑信息
            </Button>
          </Space>
        }
      >
        {currentCustomer && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <Card bordered={false}>
                <div style={{ marginBottom: 16 }}>
                  <Row gutter={[16, 16]}>
                    <Col span={12}>
                      <div>
                        <Text type="secondary">电话:</Text>
                        <div>
                          <PhoneOutlined style={{ marginRight: 8 }} />
                          {currentCustomer.contact.phoneNumber}
                        </div>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div>
                        <Text type="secondary">状态:</Text>
                        <div>
                          {getStatusTag(currentCustomer.status)}
                        </div>
                      </div>
                    </Col>
                  </Row>
                </div>
                
                <div style={{ marginBottom: 16 }}>
                  <Row gutter={[16, 16]}>
                    <Col span={12}>
                      <div>
                        <Text type="secondary">行业:</Text>
                        <div>
                          <ShopOutlined style={{ marginRight: 8 }} />
                          {currentCustomer.industry || '未设置'}
                        </div>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div>
                        <Text type="secondary">产品/服务:</Text>
                        <div>
                          <TagOutlined style={{ marginRight: 8 }} />
                          {currentCustomer.product || '未设置'}
                        </div>
                      </div>
                    </Col>
                  </Row>
                </div>
                
                <div style={{ marginBottom: 16 }}>
                  <Row gutter={[16, 16]}>
                    <Col span={12}>
                      <div>
                        <Text type="secondary">位置:</Text>
                        <div>
                          <EnvironmentOutlined style={{ marginRight: 8 }} />
                          {currentCustomer.location || '未设置'}
                        </div>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div>
                        <Text type="secondary">来源:</Text>
                        <div>
                          <InfoCircleOutlined style={{ marginRight: 8 }} />
                          {currentCustomer.source || '未设置'}
                        </div>
                      </div>
                    </Col>
                  </Row>
                </div>
                
                <div style={{ marginBottom: 16 }}>
                  <Row gutter={[16, 16]}>
                    <Col span={12}>
                      <div>
                        <Text type="secondary">下次跟进:</Text>
                        <div>
                          <CalendarOutlined style={{ marginRight: 8 }} />
                          {currentCustomer.nextFollowUp 
                            ? moment(currentCustomer.nextFollowUp).format('YYYY-MM-DD')
                            : '未设置'}
                        </div>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div>
                        <Text type="secondary">评分:</Text>
                        <div>
                          {Array.from({ length: 5 }).map((_, index) => (
                            <StarOutlined 
                              key={index} 
                              style={{ 
                                fontSize: '16px',
                                color: index < (currentCustomer.rating || 0) ? '#faad14' : '#d9d9d9',
                                marginRight: '3px',
                                cursor: 'pointer'
                              }} 
                              onClick={() => handleRatingChange(currentCustomer.id, index + 1)}
                            />
                          ))}
                        </div>
                      </div>
                    </Col>
                  </Row>
                </div>
                
                <div>
                  <Text type="secondary">备注:</Text>
                  <div style={{ background: '#f9f9f9', padding: 8, borderRadius: 4, marginTop: 4 }}>
                    {currentCustomer.notes || '暂无备注'}
                  </div>
                </div>
              </Card>
            </TabPane>
            
            <TabPane tab="最近消息" key="2">
              <Card bordered={false}>
                {recentMessages.length > 0 ? (
                  <div>
                    {recentMessages.map(message => (
                      <div 
                        key={message.id} 
                        style={{ 
                          marginBottom: 16, 
                          padding: 12, 
                          borderRadius: 8, 
                          background: message.fromMe ? '#e6f7ff' : '#f5f5f5',
                          textAlign: message.fromMe ? 'right' : 'left'
                        }}
                      >
                        <div style={{ marginBottom: 4, fontSize: 12, color: '#888' }}>
                          {moment(message.timestamp).format('YYYY-MM-DD HH:mm:ss')}
                        </div>
                        <div>
                          {message.type === 'text' ? (
                            message.body
                          ) : (
                            <span>
                              <FileTextOutlined /> {message.mediaType || '文件'} 消息
                            </span>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div style={{ textAlign: 'center', padding: 24 }}>
                    <Empty description="暂无最近消息" />
                  </div>
                )}
              </Card>
            </TabPane>
          </Tabs>
        )}
      </Drawer>

      {/* 新增筛选条件对话框 */}
      <Modal
        title="筛选客户"
        open={filterModalVisible}
        onCancel={() => setFilterModalVisible(false)}
        onOk={() => filterForm.submit()}
        width={500}
        destroyOnClose
        footer={[
          <Button key="clear" onClick={handleClearFilters}>
            清空筛选
          </Button>,
          <Button key="cancel" onClick={() => setFilterModalVisible(false)}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={() => filterForm.submit()}>
            应用筛选
          </Button>,
        ]}
      >
        <Form
          form={filterForm}
          layout="vertical"
          name="filterForm"
          onFinish={handleFilterSubmit}
        >
          <Form.Item name="keyword" label="关键词搜索">
            <Input placeholder="搜索客户名称、电话、产品等" prefix={<SearchOutlined />} />
          </Form.Item>
          
          <Form.Item name="status" label="客户状态">
            <Select allowClear placeholder="选择客户状态">
              <Option value="lead">潜在客户</Option>
              <Option value="prospect">意向客户</Option>
              <Option value="customer">成交客户</Option>
              <Option value="inactive">非活跃客户</Option>
            </Select>
          </Form.Item>
          
          <Form.Item name="industry" label="行业">
            <Select allowClear placeholder="选择行业">
              <Option value="制造业">制造业</Option>
              <Option value="服务业">服务业</Option>
              <Option value="零售业">零售业</Option>
              <Option value="教育">教育</Option>
              <Option value="医疗">医疗</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          
          <Form.Item name="source" label="客户来源">
            <Select allowClear placeholder="选择客户来源">
              <Option value="推荐">推荐</Option>
              <Option value="网站">网站</Option>
              <Option value="广告">广告</Option>
              <Option value="展会">展会</Option>
              <Option value="社交媒体">社交媒体</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          
          <Form.Item name="dateRange" label="创建日期范围">
            <RangePicker style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加客户对话框 */}
      <Modal
        title="添加新客户"
        open={addModalVisible}
        onCancel={() => setAddModalVisible(false)}
        onOk={handleAddCustomer}
        width={600}
        destroyOnClose
      >
        <Form
          form={addForm}
          layout="vertical"
          name="addCustomerForm"
          initialValues={{ status: 'lead' }}
        >
          <Form.Item
            name="name"
            label="客户姓名"
            rules={[{ required: true, message: '请输入客户姓名' }]}
          >
            <Input placeholder="输入客户姓名" prefix={<UserOutlined />} />
          </Form.Item>
          
          <Form.Item
            name="phoneNumber"
            label="电话号码"
            rules={[{ required: true, message: '请输入电话号码' }]}
          >
            <Input placeholder="输入电话号码" prefix={<PhoneOutlined />} />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="客户状态"
            rules={[{ required: true, message: '请选择客户状态' }]}
          >
            <Select>
              <Option value="lead">潜在客户</Option>
              <Option value="prospect">意向客户</Option>
              <Option value="customer">成交客户</Option>
              <Option value="inactive">非活跃客户</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="industry"
            label="行业"
          >
            <Select allowClear placeholder="选择行业">
              <Option value="制造业">制造业</Option>
              <Option value="服务业">服务业</Option>
              <Option value="零售业">零售业</Option>
              <Option value="教育">教育</Option>
              <Option value="医疗">医疗</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="product"
            label="产品/服务"
          >
            <Input placeholder="客户感兴趣的产品或服务" />
          </Form.Item>
          
          <Form.Item
            name="quantity"
            label="数量/规模"
          >
            <Input placeholder="意向采购数量或规模" />
          </Form.Item>
          
          <Form.Item
            name="location"
            label="位置"
          >
            <Input placeholder="客户所在地区" prefix={<EnvironmentOutlined />} />
          </Form.Item>
          
          <Form.Item
            name="source"
            label="客户来源"
          >
            <Select allowClear placeholder="选择客户来源">
              <Option value="推荐">推荐</Option>
              <Option value="网站">网站</Option>
              <Option value="广告">广告</Option>
              <Option value="展会">展会</Option>
              <Option value="社交媒体">社交媒体</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="nextFollowUp"
            label="下次跟进时间"
          >
            <DatePicker 
              style={{ width: '100%' }} 
              placeholder="选择跟进日期"
              format="YYYY-MM-DD"
            />
          </Form.Item>
          
          <Form.Item
            name="notes"
            label="备注"
          >
            <TextArea rows={4} placeholder="添加客户备注信息" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CustomerManagement; 